﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exercise_logic.dart';
import '../../../core/models/exercise_info.dart';

/// 锻炼选择页面
class ExerciseView extends GetView<ExerciseLogic> {
  const ExerciseView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text(
          '选择运动',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.search, color: Colors.white),
            onPressed: () => _showSearchDialog(),
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            _buildFilterBar(),
            Expanded(
              child: Obx(() {
                if (controller.state.isLoading.value) {
                  return const Center(
                    child: CircularProgressIndicator(color: Colors.orange),
                  );
                }
                return _buildExerciseList();
              }),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建筛选栏
  Widget _buildFilterBar() {
    return Container(
      height: 60.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Obx(() => Row(
                children: [
                  _buildFilterChip(
                    '全部',
                    controller.state.selectedTriggerType.value.isEmpty,
                    () => controller.selectTriggerType(null),
                  ),
                  SizedBox(width: 8.w),
                  ...controller.getTriggerTypes().map((triggerType) {
                    return Padding(
                      padding: EdgeInsets.only(right: 8.w),
                      child: _buildFilterChip(
                        controller.getTriggerTypeName(triggerType),
                        controller.state.selectedTriggerType.value == triggerType,
                        () => controller.selectTriggerType(triggerType),
                      ),
                    );
                  }).toList(),
                ],
              )),
            ),
          ),
          SizedBox(width: 8.w),
          Obx(() => IconButton(
            onPressed: controller.toggleGpsFilter,
            icon: Icon(
              Icons.gps_fixed,
              color: controller.state.showGpsOnly.value ? Colors.orange : Colors.grey,
              size: 20.sp,
            ),
          )),
        ],
      ),
    );
  }

  /// 构建筛选芯片
  Widget _buildFilterChip(String label, bool isSelected, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
        decoration: BoxDecoration(
          color: isSelected ? Colors.orange : Colors.grey[800],
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(
            color: isSelected ? Colors.orange : Colors.grey[600]!,
            width: 1,
          ),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.black : Colors.white,
            fontSize: 12.sp,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  /// 构建运动列表
  Widget _buildExerciseList() {
    return Obx(() {
      final exercises = controller.state.displayedExerciseTypes;
      
      if (exercises.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.search_off,
                size: 48.sp,
                color: Colors.grey[600],
              ),
              SizedBox(height: 16.h),
              Text(
                '没有找到相关运动',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 16.sp,
                ),
              ),
              SizedBox(height: 8.h),
              TextButton(
                onPressed: controller.clearFilters,
                child: Text(
                  '清除筛选条件',
                  style: TextStyle(
                    color: Colors.orange,
                    fontSize: 14.sp,
                  ),
                ),
              ),
            ],
          ),
        );
      }

      return ListView.separated(
        padding: EdgeInsets.all(16.w),
        itemCount: exercises.length,
        separatorBuilder: (context, index) => Divider(
          color: Colors.grey[800],
          height: 1,
        ),
        itemBuilder: (context, index) {
          final exercise = exercises[index];
          return _buildExerciseItem(exercise);
        },
      );
    });
  }

  /// 构建运动项
  Widget _buildExerciseItem(ExerciseInfo exercise) {
    return GestureDetector(
      onTap: () => controller.selectExerciseType(exercise),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 4.w),
        child: Row(
          children: [
            // 运动图标
            Container(
              width: 50.w,
              height: 50.w,
              decoration: BoxDecoration(
                color: Colors.orange.withOpacity(0.2),
                borderRadius: BorderRadius.circular(25.r),
              ),
              child: Center(
                child: Icon(
                  _getExerciseIcon(exercise.exerciseName),
                  color: Colors.orange,
                  size: 24.sp,
                ),
              ),
            ),
            SizedBox(width: 16.w),
            
            // 运动信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        exercise.exerciseName,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      if (exercise.hasGps) ...[
                        SizedBox(width: 8.w),
                        Icon(
                          Icons.gps_fixed,
                          color: Colors.orange,
                          size: 16.sp,
                        ),
                      ],
                    ],
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    _getExerciseDescription(exercise),
                    style: TextStyle(
                      color: Colors.grey[400],
                      fontSize: 12.sp,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 4.h),
                  Row(
                    children: [
                      Icon(
                        Icons.category,
                        color: Colors.blue[400],
                        size: 14.sp,
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        controller.getTriggerTypeName(exercise.triggerType),
                        style: TextStyle(
                          color: Colors.grey[500],
                          fontSize: 10.sp,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            
            // 箭头
            Icon(
              Icons.chevron_right,
              color: Colors.grey[600],
              size: 24.sp,
            ),
          ],
        ),
      ),
    );
  }

  /// 获取运动图标
  IconData _getExerciseIcon(String exerciseName) {
    if (exerciseName.contains('跑步')) return Icons.directions_run;
    if (exerciseName.contains('散步')) return Icons.directions_walk;
    if (exerciseName.contains('徒步')) return Icons.hiking;
    if (exerciseName.contains('越野')) return Icons.terrain;
    return Icons.fitness_center;
  }

  /// 获取运动描述
  String _getExerciseDescription(ExerciseInfo exercise) {
    if (exercise.isIndoor) return '适合室内锻炼';
    if (exercise.isOutdoor) return '适合户外锻炼';
    if (exercise.hasGps) return '支持GPS轨迹记录';
    return '保持健康，享受运动';
  }

  /// 显示搜索对话框
  void _showSearchDialog() {
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.grey[900],
        title: Text(
          '搜索运动',
          style: TextStyle(color: Colors.white, fontSize: 18.sp),
        ),
        content: TextField(
          autofocus: true,
          style: const TextStyle(color: Colors.white),
          decoration: InputDecoration(
            hintText: '输入运动名称...',
            hintStyle: TextStyle(color: Colors.grey[400]),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8.r),
              borderSide: BorderSide(color: Colors.grey[600]!),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8.r),
              borderSide: BorderSide(color: Colors.grey[600]!),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8.r),
              borderSide: const BorderSide(color: Colors.orange),
            ),
            prefixIcon: const Icon(Icons.search, color: Colors.grey),
          ),
          onChanged: (value) {
            controller.setSearchKeyword(value);
          },
          onSubmitted: (value) {
            Get.back();
          },
        ),
        actions: [
          TextButton(
            onPressed: () {
              controller.setSearchKeyword('');
              Get.back();
            },
            child: Text(
              '清除',
              style: TextStyle(color: Colors.grey[400]),
            ),
          ),
          TextButton(
            onPressed: () => Get.back(),
            child: const Text(
              '确定',
              style: TextStyle(color: Colors.orange),
            ),
          ),
        ],
      ),
    );
  }
}
